package com.tieto.springboot.demo.customsession;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Component;

import redis.clients.jedis.Jedis;

@Component("sessionFilter")
public class CustomSessionFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		if(!(request instanceof CustomHttpServletRequestWrapper)){			
			String sessionId = null;
			HttpServletRequest httpServletRequest = (HttpServletRequest)request;
			
			Cookie[] cookies = httpServletRequest.getCookies();
			if(cookies != null){			
				for(Cookie cookie : cookies){
					if(cookie.getName().equals("tietoSession")){
						sessionId = cookie.getValue();
					}
				}
			}
			if(sessionId == null){
				sessionId = UUID.randomUUID().toString();
				
				Cookie cookie = new Cookie("tietoSession", sessionId);
				cookie.setMaxAge(-1);
				cookie.setValue(sessionId);
				cookie.setPath(httpServletRequest.getContextPath());
				((HttpServletResponse)response).addCookie(cookie);
			}
			chain.doFilter(new CustomHttpServletRequestWrapper(sessionId, httpServletRequest), response);
		}
		else{
			refreshJedisExpireTime(request);//refresh expire time of sessionId in Redis
			
			chain.doFilter(request, response);
		}
		
	}

	@Override
	public void destroy() {}
	
	private void refreshJedisExpireTime(ServletRequest request){
		HttpSession session = ((CustomHttpServletRequestWrapper)request).getSession();
		int maxInactiveInterval = session.getMaxInactiveInterval();
		String sessionId = session.getId();
		
		Jedis jedis = JedisPoolUtil.getJedis();
		jedis.expire(sessionId, maxInactiveInterval);
		jedis.close();
	}

}
